<script setup>
import { getRoleMenus, allocateRoleMenus } from '@/api/roles';
import { useRoute, useRouter } from 'vue-router';
import { ref, defineProps } from 'vue';
import { ElMessage } from 'element-plus';

const route = useRoute();
const router = useRouter(); // 确保你已经导入了 useRouter 并使用了它

console.log(route.params.roleId);

// 定义 props
const props = defineProps({
  roleId: {
    type: String,
    required: true
  }
});

// 存储数据
const roleMenus = ref([]);
// 默认被选中的key
const checkedIds = ref([]);

// 获取所有被选中的菜单ID
const getCheckedIds = (arrData) => {
  arrData.forEach((roleMenu) => {
    if (roleMenu.subMenuList && roleMenu.subMenuList.length > 0) {
      getCheckedIds(roleMenu.subMenuList);
    } else if (roleMenu.selected) {
      checkedIds.value.push(roleMenu.id);
    }
  });
};

// 获取数据
const loadRoleMenus = async () => {
  try {
    const { data } = await getRoleMenus(props.roleId);
    if (data.code === '000000') {
      roleMenus.value = data.data;
      // 获取所有被选中的菜单ID
      getCheckedIds(data.data);
    } else {
      ElMessage.error('获取角色菜单权限信息失败');
      throw new Error('获取角色菜单权限信息失败');
    }
  } catch (error) {
    console.error(error);
  }
};

loadRoleMenus();

// 创建与引用标识相同的变量名称
const menuTree = ref(null);

// 保存更新后的数据
const onSave = async () => {
  const currentCheckedIds = menuTree.value.getCheckedKeys();
  // 把最新数据（ID数组）通过接口发给服务端
  try {
    const { data } = await allocateRoleMenus(props.roleId, currentCheckedIds);
    if (data.code === '000000' && data.data) {
      ElMessage.success('更新角色菜单权限成功');
      router.push({ name: 'roles' }); // 使用 router 进行导航
    } else {
      ElMessage.error('更新角色菜单权限失败');
      throw new Error('更新角色菜单权限失败');
    }
  } catch (error) {
    console.error(error);
  }
};

// 清空所有
const onClear = () => {
  menuTree.value.setCheckedKeys([]);
};
</script>

<template>
  <el-tree
    ref="menuTree"
    :data="roleMenus"
    :props="{ label: 'name', children: 'subMenuList' }"
    show-checkbox
    default-expand-all
    node-key="id"
    :default-checked-keys="checkedIds"
  />
  <el-button type="primary" @click="onSave">保存</el-button>
  <el-button type="primary" @click="onClear">清空</el-button>
</template>

<style scoped>
.el-tree {
  margin-bottom: 17px;
}
</style>
